﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;

namespace Sol_File.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class UploadFileController : ControllerBase
    {
        [HttpPost("UploadFile")]
        public ActionResult<string> UploadFile()
        {
            string result = string.Empty;
            try
            {
                try
                {
                    var files = HttpContext.Request.Form.Files;
                    var file = files[0];
                    Stream stream = file.OpenReadStream();

                    string userid = Request.Query["userid"];

                    #region 解析xml

                    //StreamReader reader = new StreamReader(stream);
                    //string text = reader.ReadToEnd();//读取txt、XML等文件内容
                    //System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
                    //doc.LoadXml(text);
                    //var node = doc.SelectSingleNode("Key").ChildNodes[0];
                    //var id = node.SelectSingleNode("ID").InnerText;

                    #endregion 解析xml

                    result = "Sucessfully";
                }
                catch (Exception ce)
                {
                    ModelState.AddModelError("Error", ce.Message);
                    return BadRequest(ModelState);
                }
            }
            catch (Exception ce)
            {
                result = ce.ToString();
            }

            return Ok(new { result });
        }

        [HttpPost("Base")]
        public ActionResult<string> Base([FromBody]fileinfo fi)
        {
            string result = string.Empty;
            try
            {
                string base64str = fi.Base.ToString().Split(',')[1];
                byte[] data = Convert.FromBase64String(base64str);
                Stream stream = new MemoryStream(data);

                result = "Sucessfully";
            }
            catch (Exception ce)
            {
                result = ce.ToString();
            }
            return Ok(new { result });
        }

        /// <summary>
        /// 将 Stream 转成 byte[]
        /// </summary>
        /// <param name="stream"></param>
        /// <returns></returns>
        public byte[] StreamToBytes(Stream stream)
        {
            byte[] bytes = new byte[stream.Length];
            stream.Read(bytes, 0, bytes.Length);
            // 设置当前流的位置为流的开始
            stream.Seek(0, SeekOrigin.Begin);
            return bytes;
        }

        /// <summary>
        /// 将 byte[] 转成 Stream
        /// </summary>
        /// <param name="stream"></param>
        /// <returns></returns>
        public Stream BytesToStream(byte[] bytes)
        {
            Stream stream = new MemoryStream(bytes);
            return stream;
        }

        /// <summary>
        /// 获取请求头测试,需要添加请求头信息，不是在URL后面加
        /// </summary>
        /// <returns></returns>
        [HttpGet("GetHead")]
        public ActionResult<string> GetHead()
        {
            var head = GetHeadParam(Request.Headers, "account");
            return head;
        }

        #region 获取的请求头值（根据请求头的key获取value）
        private string GetHeadParam(IHeaderDictionary Headers, string searchKey)
        {
            string result = string.Empty;
            try
            {
                var itemHead = Headers.Where(c => c.Key == searchKey).FirstOrDefault();
                result = itemHead.Value;
                //result = Newtonsoft.Json.JsonConvert.SerializeObject(Headers,Newtonsoft.Json.Formatting.Indented);
            }
            catch (Exception e)
            {
                throw e;
            }
            return result;
        }
        #endregion
    }

    public class fileinfo
    {
        public string filename { get; set; }
        public object Base { get; set; }
    }
}